package 初级.整数反转;

/**
 * 教程:https://leetcode-cn.com/problems/reverse-integer/solution/tu-jie-7-zheng-shu-fan-zhuan-by-wang_ni_ma/
 */
public class Solution {
    public static void main(String[] args) {
        System.out.println(reverse2(123123));
    }

    /**
     * 自己做的
     * @param x
     * @return
     */
    public static int reverse(int x) {
        try {
            String str=String.valueOf(x);//转化为string
            StringBuilder res = new StringBuilder();
            boolean flag=true;//标志位
            if(x>0){
                char[] chars = new char[str.length()];//数组
                //遍历转化为数组
                for (int i = 0; i < str.length(); i++) {
                    chars[i] = str.charAt(i);
                }

                //从后往前遍历数组
                for (int i = chars.length-1; i >=0 ; i--) {
                    if (chars[i]!='0'&&flag){//末尾不等于0
                        res.append(chars[i]);
                        flag=false;
                    }else {
                        res.append(chars[i]);
                    }
                }
                return Integer.parseInt(res.toString());
            }else if(x<0){
                str=str.substring(1, str.length());
                char[] chars = new char[str.length()];//数组
                //遍历转化为数组
                for (int i = 0; i < str.length(); i++) {
                    chars[i] = str.charAt(i);
                }

                //从后往前遍历数组
                for (int i = chars.length-1; i >=0 ; i--) {
                    if (chars[i]!='0'&&flag){//末尾不等于0
                        res.append(chars[i]);
                        flag=false;
                    }else {
                        res.append(chars[i]);
                    }
                }
                res.insert(0, '-');
                return Integer.parseInt(res.toString());
            }else{
                return x;//0
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 参考代码
     */
    public static int reverse2(int x){
        int res = 0;//结果
        int temp = 0;
        //每次都模10，除10，直到x=0
        while (x != 0){
            temp = x%10;

            //判断是否溢出，溢出则返回0
            if ((res>Integer.MAX_VALUE/10) || (res==Integer.MAX_VALUE/10 && temp>7)){
                return 0;
            }
            if ((res<Integer.MIN_VALUE/10) || (res==Integer.MIN_VALUE/10 && temp<-8)){
                return 0;
            }

            //拼接res
            res=res*10+temp;
            //当前x/10
            x/=10;
        }
        return res;
    }
}
